package com.itheima.youdianda.controller;

import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.CommonImgDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${youdianda.basePath}")
    private String basePath;

    @PostMapping("/upload")
    public R upload(@RequestBody MultipartFile file, String type){

        //获取用户上传的文件名
        String originalFilename = file.getOriginalFilename();
        /*获取文件名的后缀名
         * 1.获取"." 的索引位置
         * 2.获取从"."开始后面的字符串
         * 3.获取 后缀名".xxx"
         */
        String fileName = null;
        if (originalFilename!=null){
            fileName= UUID.randomUUID()+ originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String savePath = "upload/"+type+"/"+ sdf.format(new Date());
        File newFile = new File(basePath +savePath );
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        try {
            file.transferTo(new File(newFile,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        CommonImgDto commonImgDto = new CommonImgDto();
        commonImgDto.setSavePath(savePath+"/"+fileName);
        commonImgDto.setMime(type);
        commonImgDto.setName(fileName);
        commonImgDto.setSize((int)file.getSize());
        return R.success(commonImgDto);
    }

}